import { useQuery } from "@tanstack/react-query";

import type { UserSummary } from "@/contexts/auth-context";
import { useAuth } from "@/contexts/auth-context";
import { useApiFetch } from "@/lib/api-fetcher";

export function useMeQuery(initialData?: UserSummary | null) {
  const fetcher = useApiFetch();
  const { tokens, updateUser } = useAuth();

  return useQuery<UserSummary | null, Error>({
    queryKey: ["auth", "me"],
    queryFn: async () => {
      if (!tokens) {
        return null;
      }

      const data = await fetcher<UserSummary>({ path: "/auth/me" });
      updateUser(data);
      return data;
    },
    initialData: initialData ?? null,
    enabled: Boolean(tokens),
    staleTime: 60 * 1000,
  });
}
